<?php
require_once('Kbs/Controller/Action.php');

class BlogController extends Kbs_Controller_Action 
{
    static $caching = false;

    public function init()
    {
        $this->view->css()->append('geshiPhp.css')
                          ->append('geshiHtml.css')
                          ->append('geshiJavascript.css');

        /* Should be open in production !!!!!!!!
         * Should be open in production !!!!!!!!
         * Should be open in production !!!!!!!!
         
        $frontendOptions = array(
           'lifetime' => 7200, 
           //'debug_header' => true,
           'regexps' => array(
                            '^/' => array('cache' => false),
                            '^/blog/' => array('cache' => false),
                            '^/blog/index' => array('cache' => false),
                            '^/blog/list' => array('cache' => true),
                            '^/blog/list/category/1' => array('cache' => true),
                       ),
           'default_options' => array(
                'cache_with_get_variables' => true,
                'cache_with_post_variables' => true,
                'make_id_with_cookie_variables' => true,
                'cache_with_session_variables' => true,
                'cache_with_files_variables' => true,
                'cache_with_cookie_variables' => true,
            )
        );

        $backendOptions = array(
            'cache_dir' => PROJECT_ROOT . '/repository/cache/' 
        );

        $cache = Zend_Cache::factory('Page', 
                                     'File', 
                                     $frontendOptions, 
                                     $backendOptions);
        $cache->start();
      */
    }

    public function indexAction() 
    {
        $this->_forward('list');
    }

    public function listAction()
    {
        if ($this->getRequest()->isGet()) {
            $this->view->categoryId = $this->_getParam('category');
            $this->view->postId = $this->_getParam('post');
        }

        if (self::$caching) {
            $cache = Kbs::initCache('Postlist');
            $id = $cache->id . Kbs::initLocale();
            $html = $cache->load($id);
            if(false == $html) {
                $html = $this->getPostslist($this->view->categoryId, $this->view->postId);
                $cache->save($html, $id, $cache->tags);
            }
        } else {
            $html = $this->getPostslist($this->view->categoryId, $this->view->postId);
        }

        $this->view->list = $html;
    }

    public function pdfAction()
    {
        if ($this->getRequest()->isGet()) {
            $id = $this->_getParam('post');
            $postObj = new Kbs_Model_Business_Post();
            $post = $postObj->getPostsListByLocale(null, $id);
            $post = $post[0];



            define('K_TCPDF_EXTERNAL_CONFIG', true);
            define('K_PATH_IMAGES', $this->view->serverUrl() . $this->view->pathImg);
            require_once('Kbs/Config/tcpdf_config_alt.php');
            require_once('tcpdf/config/lang/eng.php');
            require_once('tcpdf/tcpdf.php');

            // create new PDF document
            $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

            // set document information
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('Kim');
            $pdf->SetTitle($post->getPostUrlTitle());
            $pdf->SetSubject($post->getPostUrlTitle());
            $pdf->SetKeywords('');

            // set default header data
            $pdf->SetHeaderData(PDF_HEADER_LOGO,
                                intval(60/2.835),
                                '',
                                PDF_HEADER_STRING);

            // set header and footer fonts
            $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
            $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

            // set default monospaced font
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

            //set margins
            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
            $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

            //set auto page breaks
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

            //set image scale factor
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 

            //set some language-dependent strings
            $pdf->setLanguageArray($l);



            //$pdf->SetFont('dejavusans', '', 10);
            $pdf->SetFont(PDF_FONT_NAME_MAIN, '', 10);

            // add a page
            $pdf->AddPage();

            $pdf->writeHTML(
                $post->fetchDetailByLocale()->getDetailContent(),
                true, 0, true, 0
            );

            // reset pointer to the last page
            $pdf->lastPage();
            //var_dump($pdf);
            $pdf->Output($post->getPostUrlTitle() . '.pdf', 'I');



            die;
        }
    }

    /*
    public function searchAction()
    {
        if ($this->getRequest()->isPost()) {
            $searchTags = trim($this->_getParam('searchTags'));
            if (!empty($searchTags)) {
                $searchCondition = $this->_getParam('searchCondition');
                $tags = preg_split('/[\s]+/', $searchTags);

                $posts = array();

                switch ($searchCondition) {
                    case 'Title':
                        $sql = "SELECT `kbs_post`.*, `kbs_post_detail`.* "
                             . "FROM `kbs_post`, `kbs_post_detail` "
                             . "WHERE `kbs_post_detail`.detail_post_id = `kbs_post`.post_id ";
                        foreach ($tags as $tag) {
                            $likes[] = " `kbs_post_detail`.detail_title LIKE '%$tag%' ";
                        }
                        $sql .= "AND (" . implode(' OR ', $likes) . ") ";
                        break;

                    case 'Content':
                        $sql = "SELECT `kbs_post`.*, `kbs_post_detail`.* "
                             . "FROM `kbs_post`, `kbs_post_detail` "
                             . "WHERE `kbs_post_detail`.detail_post_id = `kbs_post`.post_id ";
                        foreach ($tags as $tag) {
                            $likes[] = " `kbs_post_detail`.detail_content LIKE '%$tag%' ";
                        }
                        $sql .= "AND (" . implode(' OR ', $likes) . ") ";
                        break;

                    case 'Both':
                    default:
                        $sql = "SELECT `kbs_post`.*, `kbs_post_detail`.* "
                             . "FROM `kbs_post`, `kbs_post_detail` "
                             . "WHERE `kbs_post_detail`.detail_post_id = `kbs_post`.post_id ";
                        foreach ($tags as $tag) {
                            $likes[] = " `kbs_post_detail`.detail_title LIKE '%$tag%' ";
                            $likes[] = " `kbs_post_detail`.detail_content LIKE '%$tag%' ";
                        }
                        $sql .= "AND (" . implode(' OR ', $likes) . ") ";
                        break;
                }

                $db = Zend_Db_Table_Abstract::getDefaultAdapter();
                $posts = $db->fetchAll($sql);

                if (!empty($posts)) {
                    $paginator = Zend_Paginator::factory($posts);
                    $page = $this->_getParam('page');
                    $paginator->setCurrentPageNumber($page);
                    $paginator->setItemCountPerPage(5);

                    if (count($paginator)) {
                        $this->view->posts = $paginator;
                        $pc = $this->view->paginationControl($paginator, 'Sliding', 'blog/paginationControl.phtml');

                        $html .= $pc
                               . $this->view->render('blog/post.phtml')
                               . $pc;
                    }
                }
                //var_dump($result);die;
            }
        }

        //$this->_forward('list');
    }
    */

    /**
     * To get the post(s)
     */
    public function getPostslist($categoryId = null, $postId = null)
    {
        $postObj = new Kbs_Model_Business_Post();
        $posts = $postObj->getPostsListByLocale($categoryId, $postId);

        $html = '';

        if (!empty($posts)) {
            $paginator = Zend_Paginator::factory($posts);
            $page = $this->_getParam('page');
            $paginator->setCurrentPageNumber($page);
            $paginator->setItemCountPerPage(5);

            if (count($paginator)) {
                $this->view->posts = $paginator;
                $pc = $this->view->paginationControl($paginator, 'Sliding', 'blog/paginationControl.phtml');

                $html .= $pc
                       . $this->view->render('blog/post.phtml')
                       . $pc;
            }
            // if in post page
            if (isset($postId)) {
                $html .= $this->view->render('blog/comments.phtml');
            }
        }

        return $html;
    }
}
